package com.lx.java8;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

import org.junit.Test;

public class ParallelStreamDriver {

	Long max = 100000000000L;

	/**
	 * 串行，就是直接使用for循环：耗时53671
	 */
	@Test
	public void serial() {
		long sum = 0;
		long start = System.currentTimeMillis();
		for (long i = 0; i < max; i++) {
			sum += i;
		}
		long end = System.currentTimeMillis();
		System.out.println("总共耗时为：" + (end - start));
	}

	/**
	 * Java7并行计算：耗时：35858
	 * 比串行快，但是写代码比较复杂，需要写一个辅助的拆分类
	 */
	@Test
	public void java7parallel() {
		ForkJoinPool pool = new ForkJoinPool();
		ForkJoinTask<Long> t = new ForkCalculater(0, max);
		long sum = 0;
		long start = System.currentTimeMillis();
		Long invoke = pool.invoke(t);
		long end = System.currentTimeMillis();
		System.out.println("总共耗时为：" + (end - start));
	}
	
	
	/**
	 * Java8并行流，代码非常简单，耗时：35357
	 */
	@Test
	public void java8Parallel(){
		long start = System.currentTimeMillis();
		long sum = LongStream.range(0, max)
			.parallel() //获取并行流
			.sum();
		long end = System.currentTimeMillis();
		System.out.println("总共耗时为：" + (end - start));
	}
}
